import android.content.Context
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Log
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import java.security.KeyStore
import java.util.concurrent.Executor
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey

class BiometricAuthManager(private val context: Context) {

    companion object {
        private const val KEY_NAME = "biometric_key"
        private const val KEYSTORE_NAME = "AndroidKeyStore"
        private const val TAG = "BiometricAuthManager"
    }

    private lateinit var executor: Executor
    private lateinit var biometricPrompt: BiometricPrompt
    private lateinit var promptInfo: BiometricPrompt.PromptInfo

    // 检查设备是否支持生物识别
    fun canAuthenticate(): Int {
        return try {
            val biometricManager = BiometricManager.from(context)
            biometricManager.canAuthenticate(
                BiometricManager.Authenticators.BIOMETRIC_STRONG or
                        BiometricManager.Authenticators.BIOMETRIC_WEAK
            )
        } catch (e: Exception) {
            Log.e(TAG, "生物识别检查失败: ${e.message}")
            BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE
        }
    }

    // 初始化生物识别
    fun initBiometricAuth(
        activity: FragmentActivity,
        onSuccess: (BiometricPrompt.AuthenticationResult) -> Unit,
        onError: (Int, CharSequence) -> Unit,
        onFailed: () -> Unit = {},
        onCancel: () -> Unit = {}
    ): Boolean {
        return try {
            executor = ContextCompat.getMainExecutor(activity)

            biometricPrompt = BiometricPrompt(activity, executor,
                object : BiometricPrompt.AuthenticationCallback() {
                    override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                        super.onAuthenticationError(errorCode, errString)
                        Log.d(TAG, "认证错误: $errorCode - $errString")
                        onError(errorCode, errString)
                    }

                    override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                        super.onAuthenticationSucceeded(result)
                        Log.d(TAG, "认证成功")
                        onSuccess(result)
                    }

                    override fun onAuthenticationFailed() {
                        super.onAuthenticationFailed()
                        Log.d(TAG, "认证失败")
                        onFailed()
                    }
                })

            // 构建提示信息 - 总是设置取消按钮文本
            val builder = BiometricPrompt.PromptInfo.Builder()
                .setTitle("身份验证")
                .setSubtitle("使用指纹或面部解锁")
                .setConfirmationRequired(false) // 设置为false提高兼容性
                .setNegativeButtonText("取消") // 总是设置取消按钮文本

            // 根据Android版本设置不同的配置
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                builder.setAllowedAuthenticators(
                    BiometricManager.Authenticators.BIOMETRIC_STRONG or
                            BiometricManager.Authenticators.BIOMETRIC_WEAK
                )
            }

            promptInfo = builder.build()
            true
        } catch (e: Exception) {
            Log.e(TAG, "初始化生物识别失败: ${e.message}")
            false
        }
    }

    // 显示生物识别对话框
    fun showBiometricPrompt(): Boolean {
        return try {
            if (!this::biometricPrompt.isInitialized) {
                Log.e(TAG, "生物识别未初始化")
                return false
            }
            biometricPrompt.authenticate(promptInfo)
            true
        } catch (e: Exception) {
            Log.e(TAG, "显示生物识别对话框失败: ${e.message}")
            false
        }
    }

    // 简化的生物识别状态检查
    fun getBiometricStatus(): BiometricStatus {
        return try {
            when (canAuthenticate()) {
                BiometricManager.BIOMETRIC_SUCCESS -> {
                    Log.d(TAG, "生物识别可用")
                    BiometricStatus.AVAILABLE
                }
                BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
                    Log.w(TAG, "未注册生物识别")
                    BiometricStatus.NOT_ENROLLED
                }
                BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
                    Log.w(TAG, "无生物识别硬件")
                    BiometricStatus.NO_HARDWARE
                }
                BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
                    Log.w(TAG, "生物识别硬件不可用")
                    BiometricStatus.HARDWARE_UNAVAILABLE
                }
                BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> {
                    Log.w(TAG, "需要安全更新")
                    BiometricStatus.SECURITY_UPDATE_REQUIRED
                }
                BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED -> {
                    Log.w(TAG, "不支持的生物识别")
                    BiometricStatus.UNSUPPORTED
                }
                BiometricManager.BIOMETRIC_STATUS_UNKNOWN -> {
                    Log.w(TAG, "生物识别状态未知")
                    BiometricStatus.UNKNOWN
                }
                else -> {
                    Log.w(TAG, "生物识别不可用")
                    BiometricStatus.UNAVAILABLE
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "检查生物识别状态异常: ${e.message}")
            BiometricStatus.UNAVAILABLE
        }
    }

    // 检查是否真的支持生物识别
    fun isBiometricReallyAvailable(): Boolean {
        return try {
            val status = getBiometricStatus()
            Log.d(TAG, "生物识别真实状态: $status")
            status == BiometricStatus.AVAILABLE
        } catch (e: Exception) {
            Log.e(TAG, "检查生物识别真实状态失败: ${e.message}")
            false
        }
    }

    // 取消生物识别验证
    fun cancelAuthentication() {
        try {
            if (this::biometricPrompt.isInitialized) {
                biometricPrompt.cancelAuthentication()
            }
        } catch (e: Exception) {
            Log.e(TAG, "取消认证失败: ${e.message}")
        }
    }
}

// 生物识别状态枚举
enum class BiometricStatus {
    AVAILABLE,
    NOT_ENROLLED,
    NO_HARDWARE,
    HARDWARE_UNAVAILABLE,
    SECURITY_UPDATE_REQUIRED,
    UNSUPPORTED,
    UNAVAILABLE,
    UNKNOWN
}